from flask import Flask, jsonify
from flask_restful import Resource, Api, reqparse
from flask_apscheduler import APScheduler
from apscheduler.schedulers.background import BackgroundScheduler
import datetime
import riskPoints
import news
import pathPlan


app = Flask(__name__)
api = Api(app)
scheduler = APScheduler(scheduler=BackgroundScheduler(timezone='Asia/Shanghai'))


class Config(object):
    JOBS = [
        {
            'id': 'job1',                
            'func': 'main:update_info',  
            'trigger': 'interval',    
            'hours': 6,
            'timezone': 'Asia/Shanghai'   
        }
    ]

    SCHEDULER_API_ENABLED = True


class News(Resource):
    def get(self):
        data = news.get_all_news()
        return data, 200


class RiskPoints(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('days', type=int)

    def get(self):
        args = self.parser.parse_args()
        days = args['days']
        data = riskPoints.get_riskPoints_by_days(days)

        return data, 200


class PathPlan(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('origin', type=str)
        self.parser.add_argument('destination', type=str)
        self.parser.add_argument('orilng', type=str)
        self.parser.add_argument('orilat', type=str)
        self.parser.add_argument('deslng', type=str)
        self.parser.add_argument('deslat', type=str)

    def get(self):
        args = self.parser.parse_args()
        origin = args['origin']
        destination = args['destination']
        if origin == '坐标':
            orilng = args['orilng']
            orilat = args['orilat']
        if destination == '坐标':
            deslng = args['deslng']
            deslat = args['deslat']
            data = pathPlan.get_path_avoid_riskpoints(origin, destination, orilng, orilat, deslng, deslat)
        else:
            data = pathPlan.get_path_avoid_riskpoints(origin, destination)

        return data, 200


def update_info():
    news.update_db()
    riskPoints.update_db()
    now = datetime.datetime.now()
    print(now.strftime('%Y-%m-%d %H:%M:%S'))


api.add_resource(News, '/news')
api.add_resource(RiskPoints, '/riskpoints')
api.add_resource(PathPlan, '/pathplan')

app.config.from_object(Config())
scheduler.init_app(app)
scheduler.start()


if __name__ == "__main__":
    app.run()